import React, { useEffect, useRef } from "react";
import E from "wangeditor";
import Cloud from 'leancloud-storage'
function getBase64(img, callback) { //将文件对象转换为base64编码字符串
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default function RichEditor(props) {
  let econt = useRef();
  useEffect(() => {
    console.log("富文本组件", props);
    let editor = new E(econt.current); //实例化编辑器
    editor.config.zIndex = 5; //自定义层级
    editor.config.menus = [
      //自定义菜单
      "head",
      "bold",
      "fontSize",
      "fontName",
      "italic",
      "underline",
      "strikeThrough",
      "indent",
      "lineHeight",
      "foreColor",
      "backColor",
      "link",
      "list",
      "todo",
      "justify",
      "quote",
      "emoticon",
      "image",
      // 'video',
      // 'table',
      // 'code',
      "splitLine",
      "undo",
      "redo",
    ];
    editor.config.onchange = function (newHtml) {
        console.log('onchange', newHtml) // 获取最新的 html 内容
        props.onChange(newHtml)  //将富文本内容传递给表单组件
    }
    // 配置触发 onchange 的时间频率，默认为 200ms
    editor.config.onchangeTimeout = 500; // 修改为 500ms
    editor.config.customUploadImg = function (resultFiles, insertImgFn) { //自定义图片上传
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法
        // console.log(resultFiles);
        getBase64(resultFiles[0],base64=>{
          console.log(base64);
          const file = new Cloud.File('img.png', { base64 }); //构建leancloud文件对象
          file.save().then(res=>{ //保存图片
            console.log(res);
            let {url} = res.attributes
            insertImgFn(url)
          })
        })
    
        // 上传图片，返回结果，将图片插入到编辑器中
    }
    editor.create(); //创建编辑器
  }, []);
  return <div ref={econt}>RichEditor</div>;
}
